package com.mushuilingfeng.spring.security;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author 沐水淋风
 * @date 2024/10/13
 */
@Component
public class TokenUtil {
    @Value("${jwt.secret}")
    private String jwtSecret;
    
    private BaseUser getUserByToken() {
        String token = getToken();
        if (null == token) {
            return null;
        }
        JWT jwt = JWT.create();
        jwt.setKey(jwtSecret.getBytes(StandardCharsets.UTF_8));
        jwt.parse(token);
        Object userPayload = jwt.getPayload("user");
        if (null == userPayload) {
            return null;
        }
        return JSONUtil.parse(userPayload).toBean(BaseUser.class);
    }
    
    public static String getToken() {
        HttpServletRequest currentRequest = HttpServletRequestUtil.getCurrentRequest();
        if (null == currentRequest) {
            return null;
        }
        return currentRequest.getHeader("token");
    }
    
    public static BaseUser getCurrentUser() {
        return SpringUtil.getBean(TokenUtil.class).getUserByToken();
    }
    
}
